package com.motu.vertx.module.utility.postgresql;





import java.util.List;

import io.vertx.core.Promise;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


//import com.motu.emperor.module.common.utility.ErrorWord;

import io.vertx.core.AsyncResult;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.sql.SQLClient;
import io.vertx.ext.sql.SQLConnection;
import io.vertx.ext.sql.SQLOptions;

public class PostgreUtils {
	private static final Logger logger = LoggerFactory.getLogger(PostgreUtils.class);


	/***
	 * 查询数据库，返回第一条记录
	 * @param postgreSQLClient
	 * @param sql
	 * @param params
	 * @param handler
	 */
	public static void queryJsonObjectFromDb(SQLClient postgreSQLClient, String sql, JsonArray params, Handler<AsyncResult<JsonObject>> handler) {
		//		System.out.println("queryJsonObjectFromDb test git");
		//		git pull
		postgreSQLClient.queryWithParams(sql, params, res->{
			if(res.succeeded()){
				List<JsonObject> rows = res.result().getRows();
				if (rows.isEmpty()){
					handler.handle(Future.succeededFuture(null));
				} else{
					JsonArray array = new JsonArray(rows);
					handler.handle(Future.succeededFuture(array.getJsonObject(0)));
				}
			}else{
				logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+res.cause().getMessage());
				res.cause().printStackTrace();
				handler.handle(Future.failedFuture(res.cause().getMessage()));
			}
		});
	}
	/***
	 * 查询数据库，返回异步结果
	 * @param postgreSQLClient
	 * @param sql
	 * @param params
	 * @param handler
	 */
	public static void queryJsonArrayFromDb(SQLClient postgreSQLClient, String sql, JsonArray params, Handler<AsyncResult<JsonArray>> handler) {
		if(postgreSQLClient == null) {
			handler.handle(Future.failedFuture("postgreSQLClient is null"));
		}else {
			postgreSQLClient.queryWithParams(sql, params, res->{
				if(res.succeeded()){
					List<JsonObject> rows = res.result().getRows();
					if (rows.isEmpty()){
						handler.handle(Future.succeededFuture(new JsonArray()));
					} else{
						JsonArray array = new JsonArray(rows);
						handler.handle(Future.succeededFuture(array));
					}
				}else{
					logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+res.cause().getMessage());
					res.cause().printStackTrace();
					handler.handle(Future.failedFuture(res.cause().getMessage()));
				}
			});
		}
	}
	/***
	 * 查询数据库，并返回一个future
	 * @param postgreSQLClient
	 * @param sql
	 * @param params
	 * @return
	 */
	public static Future<JsonArray> queryJsonArrayFromDb(SQLClient postgreSQLClient, String sql, JsonArray params) {
		Promise<JsonArray> fut = Promise.promise();
		postgreSQLClient.queryWithParams(sql, params, res->{
			if(res.succeeded()){
				List<JsonObject> rows = res.result().getRows();
				if (rows.isEmpty()){
					fut.complete(new JsonArray());
				} else{
					JsonArray array = new JsonArray(rows);
					fut.complete(array);
				}
			}else{
				logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+res.cause().getMessage());
				res.cause().printStackTrace();
				fut.fail(res.cause().getMessage());
			}
		});
		return fut.future();
	}

	/***
	 * 更新到数据库
	 * @param postgreSQLClient
	 * @param sql
	 * @param params
	 * @param handler
	 */
	public static void updateToDb(SQLClient postgreSQLClient,String sql,JsonArray params, Handler<AsyncResult<Object>> handler) {
		postgreSQLClient.updateWithParams(sql, params, res->{
			if(res.succeeded()){
				handler.handle(Future.succeededFuture(res.result()));
			}else{
				logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+res.cause().getMessage());
				res.cause().printStackTrace();
				handler.handle(Future.failedFuture(res.cause().getMessage()));
			}
		});

	}
	/***
	 * 插入数据库并取回自增id
	 * @param postgreSQLClient
	 * @param sql
	 * @param params
	 * @return
	 */
	public static void insertAndGetID(SQLClient postgreSQLClient,String sql,JsonArray params, Handler<AsyncResult<Long>> handler) {
		postgreSQLClient.getConnection(asyncResult -> {
			if (asyncResult.failed()) {
				logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+asyncResult.cause().getMessage());
				asyncResult.cause().printStackTrace();
				handler.handle(Future.failedFuture(asyncResult.cause().getMessage()));
			} else {
				SQLConnection connection = asyncResult.result();
				connection.setOptions(new SQLOptions().setAutoGeneratedKeys(true));
				connection.updateWithParams(sql, params,
						ar -> {
							if (ar.failed()) {
								logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+ar.cause().getMessage());
								ar.cause().printStackTrace();
								handler.handle(Future.failedFuture(ar.cause().getMessage()));
							} else {
								JsonArray array = ar.result().getKeys();
								if(!array.isEmpty()){
									Long id = (Long) array.getValue(0);
									handler.handle(Future.succeededFuture(id));
								}else{
									//									logger.error("----############---- sql:"+sql+" params:"+params.toString());
									//									handler.handle(Future.failedFuture("not increment id"));
									handler.handle(Future.succeededFuture(0l));
								}

							}
							connection.close();
						});
			}
		});
	}
	//	/***
	//	 * 获取单条数据，如"select id,username from userinfo where id = 1",返回的是不带字段名的array[1,"ibm"],如果搜索不到则返回null
	//	 * @param postgreSQLClient
	//	 * @param sql
	//	 * @param params
	//	 * @param handler
	//	 */
	//	public static void querySingleFromDb(Pool postgreSQLClient, String sql, JsonArray params, Handler<AsyncResult<JsonArray>> handler) {
	//		postgreSQLClient.querySingleWithParams(sql, params, res->{
	//			if(res.succeeded()){
	//				JsonArray array = res.result();
	//				handler.handle(Future.succeededFuture(array));
	//			}else{
	//				logger.error("----############---- sql:"+sql+" params:"+params.toString()+" "+res.cause().getMessage());
	//				res.cause().printStackTrace();
	//				handler.handle(Future.failedFuture(res.cause().getMessage()));
	//			}
	//		});
	//	}

}
